#!/bin/bash -e
# adds an article to /srv/http/a

# firstly, copy the article
article_dir="/srv/http/a"
#article_dir="/home/bob"

linebreak=false
if [ "$1" = "-b" ] ; then
	linebreak=true
	shift
fi
if [ $# -lt 1 -o "$1" = "-" ] ; then
	# either there are no arguments, or $1 is '-'
	# so we read from stdin
	# create a unique file
	article=$article_dir/$(date +%s)
	if [ -f $article ] ; then
		# for some reason it exists...
		# i don't really want to deal with that
		echo "ERROR: '$article' exists."
		exit 1
	fi

	if [ "$linebreak" = "true" -o "$2" = "-b" ] ; then
		# preserve line breaks. currently we wrap it with <pre>
		echo "<pre>" >> $article
		linebreak=true
		shift
	fi
	# put stdin
	while read line ; do echo $line >> $article ; done
	[ "$linebreak" = "true" ] && echo "</pre>" >> $article
else
	article=$1
	if [ ! -f $article ] ; then
		echo "file not found '$article'"
		exit 1
	fi
	cp $article $article_dir
fi


echo "Adding article '$article'"

# Now add it to the article table
# the table's format is as follows:
# 'article id'	'article filename'	['list of tags',...]
# ...
#
# The first tag is the name to use for the article.
# Otherwise, we use the filename

# the new ID is taken from the file 'latest.id', which is then incremented
latest_id="$article_dir/latest.id"
table="$article_dir/table"

if [ -f $latest_id ] ; then 
	ID=$(< $article_dir/latest.id)
else
	echo "WARN: lastest.id does not exist. starting at 0"
	ID=0
fi

echo $((ID + 1)) > $latest_id

printf "Adding to table.\nID:%s\nTAGS: " $ID

printf "%s\t%s" $ID $article >> $table

shift
if [ ! -z "$1" ] ; then
	# add tags
	printf "(%s)" $@
	{
	printf "\t" ;
	for i in "$@" ; do
		printf "%s;" $i
	done;
	echo; # newline
	} >> $table
else
	echo " NONE"
	article=$(basename $article)
	echo ${article%.*} >> $table
fi

echo
